<template>
  <div class="header">
    <auth-page
    @loadingToast="toastLoading" 
    :isAuth="isAuth" 
    @getUserInfo="logon"></auth-page>
    <index-page
      v-if="isAuth"
      :isAuth="isAuth"
      :userInfo="userInfo"
      :goal="goal"
      :dakaRecordLists="dakaRecordLists"
      :extraUserInfo="extraUserInfo"
      :pocket="pocket"
      :pocketType="pocketType"
      @changeTab="changeTab"
      @updateDakaRecordLists="updateDakaRecordLists"
      @reload="load"
      @updateTargetInfo="updateTargetInfo"
      @showLoading="loadingShow"
      @hideLoading="loadingHide"
      @loadingToast="toastLoading"
      @successToast="toastSuccess"
      @failToast="toastFail"
    ></index-page>
    <my-loading v-if="showLoading" />
    <tab-bar :activeIndex="0"></tab-bar>
    <van-toast id="van-toast" />
  </div>
</template>

<script>
import authPage from "./childPage/authPage";
import indexPage from "./childPage/indexPage";
import tabBar from "../../components/tabBar";
import cloudHandler from "../../cloud/index";
import { formatDay } from "../../utils/index";
import myLoading from "../../components/loading";
import Toast from "../../../static/vant/toast/toast";
export default {
  data() {
    return {
      isAuth: false,
      userInfo: null,
      goal: {},
      extraUserInfo: {},
      dakaRecordLists: [],
      pocket: [],
      pocketType: "all",
      showLoading: false
    };
  },

  components: {
    authPage,
    indexPage,
    tabBar,
    myLoading
  },

  methods: {
    toastLoading() {
      Toast.loading({
        mask: true,
        message: "加载中..."
      });
    },
    toastSuccess() {
      Toast.success({
        message: "提交成功"
      });
    },
    toastFail() {
      Toast.fail({
        message: "提交失败"
      });
    },
    loadingShow() {
      this.showLoading = true;
    },
    loadingHide() {
      this.showLoading = false;
    },
    changeTab(key) {
      this.pocketType = key;
      // this.getPocket();
    },
    // 检查注册状态
    checkLogon() {
      return cloudHandler.checkLogon().then(res => {
        if (res.body === null) {
          // 新用户
          this.isAuth = false;
        } else {
          this.isAuth = true;
          // 这里拿到的信息是基础信息（微信自带）
          this.userInfo = res.body;
          this.globalData.userInfo = this.userInfo;
        }
      });
    },
    // 注册操作
    logon(data) {
      const { userInfo } = data;
      this.globalData.userInfo = userInfo;
      this.userInfo = userInfo;
      Promise.all([cloudHandler.initCardList(), cloudHandler.logon(userInfo)])
        .then(res => {
          this.isAuth = true;
          this.getPocket();
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取目标分数
    getGoal() {
      return cloudHandler
        .getGoal()
        .then(res => {
          if (res.body) this.goal = res.body;
        })
        .catch(err => {
          console.log(err);
        });
    },
    updateTargetInfo() {
      Promise.all([this.getExtraUserInfo(), this.getGoal()])
        .then(() => {
          this.loadingHide();
        })
        .catch(() => {
          this.loadingHide();
        });
    },
    getExtraUserInfo() {
      return cloudHandler
        .getExtraUserInfo()
        .then(res => {
          if (res.body) {
            this.extraUserInfo = res.body;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    getDakaRecordLists(dateString) {
      return cloudHandler
        .getDakaRecordLists(dateString)
        .then(res => {
          if (res.body)
            this.dakaRecordLists = res.body.sort(
              (a, b) =>
                new Date(a.created_time).getTime() -
                new Date(b.created_time).getTime()
            );
          console.log(this.dakaRecordLists);
        })
        .catch(err => {
          console.log(err);
        });
    },
    updateDakaRecordLists() {
      this.getDakaRecordLists(formatDay(new Date()));
    },
    getPocket() {
      return cloudHandler
        .getPocket("all")
        .then(res => {
          if (res.body) {
            this.pocket =
              res.body &&
              res.body.filter(item => {
                return item.active;
              });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    load() {
      this.checkLogon();
      this.getGoal();
      this.getExtraUserInfo();
      this.getDakaRecordLists(formatDay(new Date()));
      this.getPocket();
    }
  },

  created() {
    this.load();
  },
  onShow() {
    this.getPocket();
  }
};
</script>

<style scoped>
.header {
  position: relative;
  min-height: 100vh;
  background: #fff;
}
</style>
